"""
|===== Conference Bot Plugin ============
|= User Commands
|===== By: ==============================
|= Patrick Kennedy
|===== Current Version: =================
|= 1.0
|===== Description: =========================================
|= Commands any user can use.
|===== Additional Comments: =================================
|= 
|============================================================"""

from utils import *
import ConfigParser, os, traceback, codecs

def cmd_away(bot, user, msg):
	"""Set yourself as away.
	Usage: )away [message]
	Type )away to toggle your status.
	While away you will not recive any messages and sending a message will make you unaway."""
	
	msg = msg.strip().lower()
	if msg in ['s','silent']:
		add_userflag(user, "options", 'silent')
	if msg or not isaway(getjid(user)):
		sub_nochat(bot, user, msg)
	else:
		sub_chat(bot, user, msg)

def sub_nochat(bot,user, msg):
	addaway(user.getStripped().lower())
	if msg:
		msg = "(%s)" % msg
	if not has_userflag(user, "options", 'silent'):
		bot.sendtoall('%s is temporarily away. %s' % (getdisplayname(user), msg), [user])
	bot.sys(user, "Warning: You have marked yourself as away. You will not recive any messages untill you use ')away' or send a message.") 
	
def sub_chat(bot, user, msg):
	if not del_userflag(user, "options", 'silent'):
		bot.sendtoall('%s is actively interested in chatting.' % (getdisplayname(user)), [user])
	delaway(user)
	bot.sys(user, 'You can begin to chat now.')

def hook_away(bot, args):
	user = getjid(args[0])
	if del_userflag(user,"status","away"):
		bot.sys(user,"Because you said something you have been marked unaway.")
	return False
	
def cmd_me(bot, user, msg):
	"""Send an action to the world.
	Usage: )me <action>"""
	if msg:
		bot.sendtoall("**%s %s**" % (getdisplayname(user), msg))
	else:
		bot.msg(user, cmd_me.__doc__)
		
def cmd_msg(bot, user, msg):
	"""Send a user a private message.
	Usage: )msg <displayname> <message>"""
	if not ' ' in msg:
		bot.msg(user, cmd_msg.__doc__)
	else:
		if has_userflag(user, "status", 'away'):
			bot.sys(user, 'Warning: Because you set "away" flag, so you can not receive and send any message from this bot, until you reset using ")away" command') 
			return
		target,msg = msg.split(' ',1)
		target = getjid(target.lower())
		if has_userflag(target,"status", 'away') and not isadmin(user):
			bot.sys(who, "<%s> has set himself 'away', so you can't message them." % getdisplayname(target)) 
			return
		#if isbusy(target):
		#	bot.sys(who, '<%s> has is busy or is idle so the message has not been delivered.' % getdisplayname(target))
		#	return
		if not isuser(bot, target):
			bot.msg(user, "The user _%s_ doesn't seem to exist." % target)
			return
		elif bot.getJidStatus(target).items() == []:
			bot.msg(user, "%s is offline and cannot receive messages." % getdisplayname(target).capitalize())
			return
		
		bot.log("<"+getdisplayname(user)+">" + " to <"+getdisplayname(target)+">", msg)
		bot.msg(target, '*<%s<* %s' % (getdisplayname(user), msg))
		bot.msg(user, '>%s> %s' % (getdisplayname(target), msg))

def cmd_photo(bot, user, msg):
        """Show the url of the conference participants' photos
        Usage: )photo"""
	bot.msg(user, "Photos: http://picasaweb.google.com/pavel.novicky/YOLVLH#")
	
def cmd_read(bot, user, msg):
	"""Read one line from a text source
	Usage: /read [<command>] <arg>
	Commands:
	charset <arg> - use <arg> charset to decode the text 
	"""
	bookCfg = ConfigParser.RawConfigParser()
	try:
		bookCfg.read( 'books.cfg' )
		#bot.sendtoall("Current book %s, current line %d" % ( bookCfg.get( 'book', 'book-file' ), bookCfg.getint( 'book', 'book-line' ) ) )
	except:
		bot.msg(user, "cannot read book cfg")
		return
	
	if 'charset' in msg:
		msg, encoding = msg.split(' ', 1)
		if encoding:
			bookCfg.set('book', 'book-charset', encoding)
			f = open( 'books.cfg', 'w' )
			bookCfg.write(f)
			bot.msg(user, "charset changed to %s" % encoding)
		return
		
	if not os.path.isfile( bookCfg.get( 'book', 'book-file' ) ):
		bot.msg(user, "book at %s doesn't exists" % ( bookCfg.get( 'book', 'book-file' ) ) )
		return
	try:
		lineNo = bookCfg.getint( 'book', 'book-line' )
		encoding = None
		if bookCfg.has_option('book', 'book-charset'):
			encoding = bookCfg.get('book', 'book-charset')
		if not encoding:
			encoding = 'utf-8'
		book = codecs.open( bookCfg.get( 'book', 'book-file' ), 'r', encoding )
		lines = book.readlines()
		if lineNo >= 0 and lineNo < len( lines ):
			while lineNo < len( lines):
				line = lines[ lineNo ]
				line = line.lstrip()
				line = line.rstrip()
				if len(line) > 0:
					break
				else:
					lineNo = lineNo + 1
			
			if lineNo < len(lines):
				bot.sendtoall( line + '\r\n' )
				lineNo = lineNo + 1
				bookCfg.set( 'book', 'book-line', "%d" % (lineNo) )
				#bot.msg(user, "--- %d" % lineNo )
				f = open( 'books.cfg', 'w' )
				bookCfg.write(f)
			else:
				bot.msg( user, "Line out of book range, reseted to 0" )
				bookCfg.set( 'book', 'book-line', "0" )
				f = open( 'books.cfg', 'w' )
				bookCfg.write(f)
				bot.sendtoall( "BOOK IS OVER!" )
		else:
			bot.msg( user, "Line out of book range, reseted to 0" )
			bookCfg.set( 'book', 'book-line', "0" )
			f = open( 'books.cfg', 'w' )
			bookCfg.write(f)
			bot.sendtoall( "BOOK IS OVER!" )
	except:
	    bot.msg(user, "cannot read book %s" % traceback.format_exc() )
	
def init(bot):
	bot.addCommand("away", cmd_away)
	bot.addHook("message", hook_away)
	bot.addCommand("me", cmd_me)
	bot.addCommand("msg", cmd_msg)
	bot.addMuteCommand("away", cmd_away)
	bot.addCommand("photo", cmd_photo)
	bot.addCommand("read", cmd_read)
